package com.outlook.util.edit;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import com.outlook.annotation.edit.EditExclude;
import com.outlook.annotation.edit.EditId;
import com.outlook.annotation.edit.EditImage;
import com.outlook.annotation.edit.EditNum;
import com.outlook.annotation.edit.EditPassword;
import com.outlook.annotation.edit.EditSelect;
import com.outlook.annotation.edit.EditString;
import com.outlook.annotation.edit.EditTitle;

/**
 * parser annotation
 * 
 * @author watson
 *
 */
@SuppressWarnings("unchecked")
public class AttributeParser {
	
	private static Class[] attributes = {EditId.class, EditTitle.class, EditNum.class, EditString.class, EditSelect.class, EditImage.class, EditPassword.class};

	public static Map<String, Object> parser(Annotation[] annotations) {
		Map<String, Object> map = new HashMap<String, Object>();
		for(Annotation annotation : annotations) {
			int index = getIndex(annotation);
			if(index>=0 && index<attributes.length) {
				map.put("name", getNameOfAnnotation(attributes[index].getName()));
				// TODO extract value from string
//				String string = annotation.toString();
//				System.out.println(string);

				Class annotationInstance = attributes[index];
				Method[] methods = annotationInstance.getDeclaredMethods();
				Object[] args = {};
				for(Method method : methods) {
					try {
						Object invoke = method.invoke(annotation, args);
						if(null != invoke) {
							map.put(method.getName(), invoke);
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			
		}
		return map;
	}

	private static Object getNameOfAnnotation(String name) {
		if(null != name) {
			String replace = name.toLowerCase().replace("@", "");
			try {
			replace = replace.substring(replace.lastIndexOf(".")+1).replace("edit", "");
			} catch (Exception e) {
				e.printStackTrace();
			}
			return replace;
		}
		return null;
	}

	private static int getIndex(Annotation annotation) {
		int index = 0;
		for(Class clazz : attributes) {
			if(annotation.annotationType().equals(clazz))
				return index;
			index++;
		}
		return -1;
	}

	public static boolean isContainExcude(Annotation[] declaredAnnotations) {
		for(Annotation annotation : declaredAnnotations) {
			if(annotation.annotationType().equals(EditExclude.class))
				return true;
		}
		return false;
	}

}